package com.itheima.interceptor;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1. 获取请求的url
        String url = request.getRequestURI().toString();

        // 2. 判断url是否是登录请求 请求路径包含/login，如果是，放行
        if (url.contains("/login")) {
            log.info("登录请求,放行");

            return true;
        }

        //3.获取请求头的token
        String jwt = request.getHeader("token");
        //4. 判断请求头中是否有token， 如果没有就响应401
        if (jwt == null || jwt.isEmpty()) {
            log.info("令牌为空，响应401");
            response.setStatus(401);
            return false;
        }

        //5.如果有就解析 ，解析失败就返回401
        try {
            Claims claims = JwtUtils.parseJWT(jwt);
//            Integer empId = Integer.valueOf(claims.get("id").toString());
//            CurrentHolder.setCurrentId(empId);//存入
//            log.info("当前员工的id是:{},将其存入ThereadLocal里", empId);

        } catch (Exception e) {
            e.printStackTrace();
            log.info("令牌非法，响应401");
            response.setStatus(401);
            return false;
        }
        //6. 解析成功就放行，解析失败就响应401
        log.info("令牌合法，放行");
//        //7. 清空当前线程绑定的id
//        CurrentHolder.remove();
        return true;

    }
}

